import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch, message } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { getUsersList, getRegionsList, roleList, addUser, updateUserInfo, delUser } from '@api'
import UserForm from './components/UserForm';

export default function UserList() {
  /*---------------------------------------定义state---------------------------------------------------------------------------*/
  /*---------------------------------------定义state---------------------------------------------------------------------------*/
  /*---------------------------------------定义state---------------------------------------------------------------------------*/
  /*---------------------------------------定义state---------------------------------------------------------------------------*/
  // 区域列表
  const [regionList, setregionList] = useState([])
  // 列表数据
  const [dataSource, setdataSource] = useState([])
  // 弹出表单
  const [isAddVisible, setisAddVisible] = useState(false)
  const [formTitle, setFormTitle] = useState('')
  // 角色列表
  const [rolesList, setroleList] = useState([])
  // 更新禁止输入
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  // 传给form表单判断是更新还是新增
  const [isUpdate,setisUpdate] = useState(false)
  // 定义表单ref
  const modalForm = useRef(null)
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render: (region) => {
        return <b>{region === "" ? '全球' : region}</b>
      },
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        })),
        {
          text: "全球",
          value: "全球"
        }
      ],
      onFilter: (value, item) => {
        if (value === "全球") {
          return item.region === "" || item.region === "全球"
        }
        return item.region === value
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role?.roleName
      }
    },
    {
      title: "用户名",
      dataIndex: 'username'
    },
    {
      title: "用户状态",
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch checked={roleState} disabled={item.default} onChange={() => changeRoleState(item)}></Switch>
      }
    },
    {
      title: "操作",
      render: (item) => {
        return <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} disabled={item.default} onClick={() => del_user(item)} />
          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={() => openModal(item)} />
        </div>
      }
    }
  ]
  // 获取用户信息
  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))
  /*--------------------------------------------------hooks调用方法-------------------------------------------------------------*/
  /*--------------------------------------------------hooks调用方法-------------------------------------------------------------*/
  /*--------------------------------------------------hooks调用方法-------------------------------------------------------------*/
  /*--------------------------------------------------hooks调用方法-------------------------------------------------------------*/
  useEffect(() => {
    get_user_list()
    get_reginon_list()
  }, [])
  /*-----------------------------------------------------定义方法----------------------------------------------------------------*/
  /*-----------------------------------------------------定义方法----------------------------------------------------------------*/
  /*-----------------------------------------------------定义方法----------------------------------------------------------------*/
  /*-----------------------------------------------------定义方法----------------------------------------------------------------*/
  // 获取用户列表
  const get_user_list = () => {
    // 角色映射对象
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    getUsersList({
      _expand: 'role'
    }).then((res) => {
      if (roleObj[roleId] === 'superadmin') {
        setdataSource(res.data)
      } else {
        let list = res.data
        let newList = [...list.filter(item => item.username === username), ...list.filter(item=>item.region === region && roleObj[item.roleId]==="editor" && item.username !== username)]
        setdataSource(newList)
      }
    })
  }
  // 获取区域列表
  const get_reginon_list = () => {
    getRegionsList().then((res) => {
      setregionList(res.data)
    })
  }
  // 点击,弹出框
  const openModal = (item) => {
    setisAddVisible(true)
    roleList().then((res) => {
      setroleList(res.data)
    })
    if (item) {
      console.log(item,88888888888);
      // 有item弹出的是更新用户
      setTimeout(() => {
        setFormTitle('更新用户信息')
        setisUpdate(true)
        if (Number(item.roleId) === 1) {
          //禁用
          setisUpdateDisabled(true)
        } else {
          //取消禁用
          setisUpdateDisabled(false)
        }
        modalForm.current.setFieldsValue(item)
      }, 0)
    } else {
      // 没有item则是新增用户
      setisUpdateDisabled(false)
      setFormTitle('新增用户')
      setisUpdate(false)
    }
  }
  // 弹出框确认
  const modalFormOK = () => {
    modalForm.current.validateFields().then((value) => {
      if (modalForm.current.getFieldValue().id) {
        // 有id则进入更新用户信息
        updateUserInfo({
          id: modalForm.current.getFieldValue().id,
          ...value
        }).then(() => {
          message.success({
            content: '更新成功 ',
          });
          setisAddVisible(false)
          get_user_list()
          modalForm.current.resetFields()
        })
      } else {
        // 没有id则进入的是新增用户
        if (dataSource.filter(item => item.username === value.username).length !== 0) {
          message.error({
            content: '该用户已存在',
          });
          return false
        } else {
          addUser({
            ...value,
            "roleState": true,
            "default": false
          }).then(() => {
            message.success({
              content: '新增成功 ',
            });
            setisAddVisible(false)
            get_user_list()
            modalForm.current.resetFields()
          })
        }
      }
    })
  }
  // 弹出框取消
  const modalFormCancel = () => {
    setisAddVisible(false)
    modalForm.current.resetFields()
  }
  // 删除用户
  const del_user = (item) => {
    Modal.confirm({
      title: '确认删除这个吗',
      icon: <ExclamationCircleOutlined style={{ color: 'red' }} />,
      content: '注意：该操作无法撤回',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        delUser(item.id).then(() => {
          message.success({
            content: '删除成功 ',
          })
          get_user_list()
        })
      }
    })
  }
  // 改变用户开启状态
  const changeRoleState = (item) => {
    updateUserInfo({
      id: item.id,
      roleState: !item.roleState
    }).then(() => {
      message.success({
        content: !item.roleState === true ? '开启成功' : '关闭成功',
      })
      get_user_list()
    })
  }
  /*-----------------------------------------------------jsx模板-----------------------------------------------------------------*/
  /*-----------------------------------------------------jsx模板-----------------------------------------------------------------*/
  /*-----------------------------------------------------jsx模板-----------------------------------------------------------------*/
  /*-----------------------------------------------------jsx模板-----------------------------------------------------------------*/
  return (
    <div>
      <Button type="primary" onClick={() => openModal()}>添加用户</Button>
      {/* 用户列表 */}
      <Table dataSource={dataSource} columns={columns} pagination={{ pageSize: 10 }} rowKey={item => item.id} />
      {/* 弹出框 */}
      <Modal visible={isAddVisible} title={formTitle} okText="确定" cancelText="取消" onCancel={() => modalFormCancel()} onOk={() => modalFormOK()}>
        {/* 表单组件 */}
        <UserForm ref={modalForm} regionList={regionList} roleList={rolesList} isUpdateDisabled={isUpdateDisabled} isUpdate={isUpdate}/>
      </Modal>
    </div>
  )
}
